import { INestApplication } from '@nestjs/common'
import os from 'os'

interface ISwaggerOption {
    title: string
    desc: string
    version: string
}

export const onProcess = (app: INestApplication) => {
    process.on('SIGINT', async () => {
        setTimeout(() => process.exit(1), 5000)
        await app.close()
        process.exit(0)
    })
    process.on('SIGTERM', async () => {
        setTimeout(() => process.exit(1), 5000)
        await app.close()
        process.exit(0)
    })
}
export const getIp = () => {
    const interfaces = os.networkInterfaces()
    let ip = '127.0.0.1'
    for (const devName in interfaces) {
        if (interfaces.hasOwnProperty(devName)) {
            const iface = interfaces[devName]
            for (const alias of iface) {
                if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                    ip = alias.address
                }
            }
        }
    }
    return ip
}

/**
 * @description: 批量加载nest模块
 * @param {array} components
 * @return {*}
 */
export const components = (...components: any[]): any => {
    const results = []
    components.forEach((component) => {
        if (typeof component === 'function') {
            results.push(component)
        } else if (!!(typeof component === 'object' && component.provide)) {
            results.push(component)
        } else if (typeof component === 'object') {
            for (const key in component) {
                const exclude = ['Interceptor', 'Filter', 'Exception']
                if (!component.hasOwnProperty(key) || exclude.some((e) => key.includes(e))) {
                    continue
                }
                results.push(component[key])
            }
        }
    })
    return results
}
/**
 * @description: 注册orm
 * @param {string} name
 * @param {*} repo
 * @return {*}
 */
export const getCustomRepository = (name: string, repo: any): any => {
    const module = require('@nestjs/typeorm')
    return {
        provide: name,
        useFactory: (connection: any) => connection.getCustomRepository(repo),
        inject: [module.getConnectionToken()],
    }
}
/**
 * @description: 批量注册orm
 * @param {array} repositories
 * @return {*}
 */
export const repositories = (...repositories: any[]): any => {
    const results = []
    repositories.forEach((repo) => {
        if (typeof repo === 'function') {
            results.push(getCustomRepository(repo.name, repo))
        } else if (typeof repo === 'object') {
            for (const key in repo) {
                if (!repo.hasOwnProperty(key)) {
                    continue
                }
                results.push(getCustomRepository(repo[key].name, repo[key]))
            }
        }
    })
    return results
}
